<?php 
/**
 * 王召波
 * @author RuoShui <963087326@qq.com>
 * 公众号: 若水小站
 */
class WeChat{
	private $appid;
	private $appsecret;
	private $toke;
	private $tpl = array(
		'text'=>'<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[text]]></MsgType>
				<Content><![CDATA[%s]]></Content>
				</xml>',
		'image'=>'<xml>
				 <ToUserName><![CDATA[%s]]></ToUserName>
				 <FromUserName><![CDATA[%s]]></FromUserName>
				 <CreateTime>%s</CreateTime>
				 <MsgType><![CDATA[text]]></MsgType>
				 <Content><![CDATA[%s]]></Content>
				 </xml>',
		'list'=>'<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<ArticleCount>%s</ArticleCount>
				<Articles>
				%s
				</Articles>
				</xml>',
		'item'=>'<item>
				<Title><![CDATA[%s]]></Title>
				<Description><![CDATA[%s]]></Description>
				<PicUrl><![CDATA[%s]]></PicUrl>
				<Url><![CDATA[%s]]></Url>
				</item>'
		);
	public function __construct($appid,$appsecret,$token){
		$this->_appid=$appid;
		$this->_appsecret = $appsecret;
		$this->_token = $token;
	}

	public function _addMedia($type, $file){
		$curl="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->_getAccesstoken()."&type=".$type;
		$data['type']=$type;
		$data['media']='@'.$file;
		$result = $this->_request($curl,true,"post",$data);
		echo $result;
	}

	public function _getuserlist(){
		$content = $this->_request("https://api.weixin.qq.com/cgi-bin/user/get?access_token=");
		$content = json_decode($content);
		$users = $content->data->openid;
		return $users;
	}
	public function _sendall($content){
		$tpl = '{
				"touser":[
				"%s"
				],
				"msgtype":"text",
				"text":{"content":"%s"}
				}';
		$users = $this->_getuserlist();
		$users = implode('","',$users);
		$data = sprintf($tpl,$users,$content);
		$curl = 'https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token='.$this->_getAccesstoken();
		$res = $this->_request($curl,true,"post",$data);
		$res = json_decode($res);
		if($res->errcode==0){
			echo "发送成功";
		}else{
			var_dump($res);
		}
	}
	public function _queryMenu(){
		$menu = $this->_request("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->_getAccesstoken());
		return $menu;
	}
	public function _deleteMenu(){
		$menu = $this->_request("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->_getAccesstoken());
		$res = json_decode($menu);
		if($res->errcode==0 and $res->errmsg=="ok"){
			echo "删除成功".$menu;
		}else{
			echo "删除失败".$menu;
		}
	}
	public function _createMenu($menu){
		$result = $this->_request("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->_getAccesstoken(),true,'post',$menu);
		$result = json_decode($resutl);
		if($result->errcode == 0){
			echo "菜单创建成功".$result;
		}else{
			echo "创建失败".$result;
		}
	}
	private function _request($curl,$https=true,$method='get',$data=null){
		$ch = curl_init();//初始化
		// 设置参数
		curl_setopt($ch,CURLOPT_URL, $curl);//设置访问的url
		curl_setopt($ch,CURLOPT_HEADER,false);//设置不需要头信息
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//只获取页面内容,但不输出 return transfer
		if($https){
			curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不做服务端认证
			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//不做客户端认证
		}
		if($method=='post'){
			curl_setopt($ch,CURLOPT_POST,true);//设置post
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//发送的数据
		}
		$str = curl_exec($ch);//执行访问,返回结果
		curl_close($ch);//关闭curl,释放资源
		return $str; 
	}
	private function _getAccesstoken(){
		$file = './accesstoken';
		if(file_exists($file)){
			$content = file_get_contents($file);
			$content = json_decode($content);
			if(time()-filemtime($file)<$content->expires_in){
				return $content->access_token;
			}
		}
		$content = $this->_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_appsecret);
		file_put_contents($file, $content);
		$content = json_decode($content);
		return $content->access_token;
	}
	/**获取
	expire_seconds:有效时间(秒),最长7天 
	type :二维码类型(临时或永久) 
	scene:场景编号
	 */
	public function _getTicket($expire_seconds = 604800,$type = "temp",$scene=1){
		if($type == "temp"){
			$data = '{"expire_seconds": '.$expire_seconds.', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}';
			return  $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->_getAccesstoken(),true,"post",$data);
		}else{
			$data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}';
			return  $this->_request("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->_getAccesstoken(),true,"post",$data);
		}
	}

	public function _getQRCode($expire_seconds,$type,$scene){
		$content = json_decode($this->_getTicket($expire_seconds,$type,$scene));
		$ticket = $content->ticket;
		$image = $this->_request("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket));
		// $file = "./".$type.$scene.".jpg";可以将二维码保存到本地,便于使用
		// file_put_contents($file,$image);保存二维码
		return $image;	
	}
	
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//获取用户发送的消息

      	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
      	switch ($postObj->MsgType) {
      		case 'event':
      			$this->_doEvent($postObj);
      			break;
      		case 'text':
      			$this->_doText($postObj);
      			break;
      		case 'image':
      			$this->_doImage($postObj);
      			break;
      		case 'voice':
      			$this->_doVoice($postObj);
      			break;
      		case 'video':
      			$this->_doVideo($postOBJ);
      			break;
      		case 'location':
      			$this->_doLocation($postObj);
      			break;
      		case 'shortvideo':
      			$this->_doShortVideo($postObj);
      			break;
      		case 'link':
      			$this->_doLink($postObj);
      			break;
      		default:
      			exit;
      			break;
      	}

	}
	private function _doEvent($postObj){
		switch($postObj->Event){
			case 'subscribe': //订阅
				$this->_doSubscribe($postObj);
				break;
			case 'unsubscribe': //取消订阅
				$this->_doUnsubscribe($postObj);
				break;
			case 'CLICK':
				$this->_doClick($postObj);
			default:
			break;
		}
	}
	private function _doSubscribe($postObj){
		$str = sprintf($this->tpl['text'],$postObj->FromUserName,$postObj->ToUserName,time(),'欢迎您关注若水的微信');
		//还可以把用户的信息保存到数据库里面
		echo $str;
	}
	private function _doUnsubscribe($postObj){
		;//把用户的信息从数据库删除
	}
	private function _doClick($postObj){
		switch($postObj->EventKey){
			case 'news':
				$news = array(
							array(
								'0'=>$this->tpl['item'],
								'Title'=>"11军改一周年：练兵场上展英姿",
								'Description'=>"2016年7月29日，在中国人民解放军陆海空三军仪仗队驻地，仪仗队步入检阅场。如果说中国人民解放军是一部厚重的史书，那么陆海空三军仪仗队就是开启这部史书的精美扉页。",
								'PicUrl'=>"http://news.xinhuanet.com/photo/2016-07/31/129192575_14699751628171n.jpg",
								'Url'=>"http://news.xinhuanet.com/photo/2016-11/26/c_1119995204.htm"
							),
							array(
								'0'=>$this->tpl['item'],
								'Title'=>"2哈哈军改一周年：练兵场上展英姿",
								'Description'=>"2016年7月29日，在中国人民解放军陆海空三军仪仗队驻地，仪仗队步入检阅场。如果说中国人民解放军是一部厚重的史书，那么陆海空三军仪仗队就是开启这部史书的精美扉页。",
								'PicUrl'=>"http://news.xinhuanet.com/photo/2016-07/31/129192575_14699751628171n.jpg",
								'Url'=>"http://news.xinhuanet.com/photo/2016-11/26/c_1119995204.htm"
							)
						); 
				//把$news数组里面的每个值都printf,返回一个格式化好的新数组
				$content=array_map(function($v){return call_user_func_array('sprintf', $v);}, $news);
				$content = implode("",$content);
				$count = count($news);
				$content = sprintf($this->tpl['list'],$postObj->FromUserName,$postObj->ToUserName,time(),$count,$content);
				echo $content;
				break;	
		}
	}
	private function _doLocation($postObj){
		$fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $time = time(); 
		$content = '您所在位置的经度'.$postObj->Location_Y.'纬度是'.$postObj->Location_Y;
		$resultStr = sprintf($this->tpl['text'],$fromUsername,$toUsername,$time,$content);;
		echo $resultStr;
	}
    private function _doText($postObj){
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        if(mb_substr($keyword, 0,2,'utf-8')=='歌曲'){
        	$this->_sendMusic($postObj);
        }    
		if(!empty( $keyword ))
        {	
        	//$data = "chat=".$keyword;
			$contentStr = $this->_request("http://www.xiaodoubi.com/bot/chat.php",false,'post',"chat=".$keyword);
        	//$contentStr = "欢迎加入若水公众号!";
        	if(strtoupper($keyword)=="PHP"){$contentStr = "世界上最流行的语言";}
        	if(strtoupper($keyword)=="JAVA"){$contentStr = "世界上较流行的语言";}
        	$resultStr = sprintf($this->tpl['text'], $fromUsername, $toUsername, $time, $contentStr);
        	echo $resultStr;
        }
        	exit;

    }
    private function _sendMusic($postObj){
    	$content = trim($postObj->Content);
    	$content = mb_substr($content,2,mb_strlen($content)-2,'utf-8');
        $arr  = explode($cutStr,'@');
        if(isset($arr[1])){
        	$curl = "http://box.zhangmen.baidu.com/x?op=12&count=1&title=".$arr[0]."$$".$arr[1]."$$$$";
        }else{
        	$curl = "http://box.zhangmen.baidu.com/x?op=12&count=1&title=".$arr[0]."$$";
        }
        $respose = $this->_request($curl,false);
        

    }
    private function _doImage($postObj){
		$str = sprintf($this->tpl['image'],$postObj->FromUserName,$postObj->$ToUserName,time(),"您发送的图片在".$postObj
			->PicUrl."  ");
		echo $str;
    }
                
    
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	public function test($content){
		$content = "chat=".$content;
		$contentStr = $this->_request("http://www.xiaodoubi.com/bot/chat.php",false,'post',$content);
		var_dump($contentStr);exit;
	}
	
}


?>